package org.alien.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;

public class DownloadThread implements Callable<DownloadTemp> {

	private int index;
	private String fileName;
	private long start, end;
	private String urlString;
	public DownloadThread() { }
	public DownloadThread(int index, long start, long end, String url, String path, String prefix) {
		this.index = index;
		this.start = start;
		this.end = end;
		this.urlString = url;
		if("".equals(path)) {
			this.fileName = prefix + "-" + index;
		} else {
			this.fileName = path + "/" + prefix + "-" + index;
		}
	}

	@Override
	public DownloadTemp call() throws Exception {
		URL url = new URL(urlString);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setRequestMethod("GET");
		httpURLConnection.setRequestProperty("Range", "byte=" + start + "-" + end);

		InputStream inputStream = httpURLConnection.getInputStream();
		File file = new File(fileName);
		OutputStream outputStream = new FileOutputStream(file);
		while(true) {
			byte[] bytes = new byte[1024];
			int length = inputStream.read(bytes);
			if(length <= 0) {
				break;
			}
			outputStream.write(bytes, 0, length);
		}
		outputStream.flush();

		if(inputStream != null)
			inputStream.close();
		if(outputStream != null)
			outputStream.close();

		DownloadTemp downloadTemp = new DownloadTemp();
		downloadTemp.setIndex(index);
		downloadTemp.setFileName(fileName);
		System.out.println("Thread\t" + index + "\tcompleted.");

		return downloadTemp;
	}








}
